package com.dongdongshop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.data.ResponseStausEnum;
import com.dongdongshop.pojo.Weather;
import com.dongdongshop.util.HttpClientUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @ClassName WeatherController
 * @Author RC
 * @date 2021.01.06 19:29
 */
@Controller
@RequestMapping("weather")
public class WeatherController {

    public static final Logger logger = LoggerFactory.getLogger(WeatherController.class);

    @RequestMapping("getWeather")
    @ResponseBody
    public DataResult getWeather(HttpServletRequest request){
//        1.创建Httpclient对象,相当于打开了浏览器
        CloseableHttpClient httpclient = HttpClients.createDefault();
//        2.创建http请求 get、post 二者选一
//          创建doget请求,相当于浏览器输入地址
        try {
            String localIp = InetAddress.getLocalHost().getHostAddress();

        } catch (UnknownHostException e) {
            logger.info("捕获异常", e);
        }
        HttpGet httpGet = new HttpGet("http://apis.juhe.cn/ip/ipNew?ip=36.112.125.94&key=0ee46e2751d0b380cfda4bc75cb33e91");
//        3.执行请求，得到响应对象
        CloseableHttpResponse response= null;
        try{
     /*       String remoteHost = request.getRemoteHost();
            System.out.println("host:>>>>>>>"+remoteHost);
            remoteHost= "36.112.125.94";
            String key = "0ee46e2751d0b380cfda4bc75cb33e91";
            String s1 = HttpClientUtil.doGetParam("http://whois.pconline.com.cn/ip.jsp", "ip","$_SERVER['REMOTE_ADDR']");
            logger.info("进入查询天气的方法");
             String s = HttpClientUtil.doGetParam("http://apis.juhe.cn/ip/ipNew","ip",remoteHost+key);*/
            response = httpclient.execute(httpGet);
//        4.判断响应状态码是不是200，获取响应数据实体对象,200表示响应成功,一般用于get和post请求
            Map<String, Object> weatherMap = new HashMap<>();

            if (response.getStatusLine().getStatusCode() == 200) {
//        5.获取响应数据
                HttpEntity entity = response.getEntity();

                String content = EntityUtils.toString(entity, "utf-8");
                System.out.println("响应结果为---->" + content);
                Map<String, Object> map = (Map<String, Object>) JSON.parse(content);
                String result = map.get("result").toString();
                Map<String, Object> map1 = (Map<String, Object>) JSON.parse(result);
                String city = map1.get("City").toString();
                String weatherMsg = HttpClientUtil.doGetParam("http://wthrcdn.etouch.cn/weather_mini", "city", city);
                System.out.println(weatherMsg);
                JSONObject weatherJson = JSONObject.parseObject(weatherMsg);
                String data = weatherJson.getObject("data", String.class);
                JSONObject jo1 = JSONObject.parseObject(data);
                System.out.println(data);
                String localCity = jo1.getString("city");
                System.out.println(city);
                String forecast = jo1.getString("forecast");
                List<Weather> weathers = JSONArray.parseArray(forecast, Weather.class);
                weathers.stream().forEach(x -> System.out.println(x));
                weatherMap.put("city", localCity);
                weatherMap.put("weathers", weathers);
            }
            return DataResult.response(ResponseStausEnum.SUSSCESS).setData(weatherMap);
        } catch (Exception e) {
            logger.info("查询失败", e);
            return DataResult.response(ResponseStausEnum.INTERNAL_SERVER_ERROR);
        }finally {
//        6.关闭响应对象
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
  //      1.创建Httpclient对象,相当于打开了浏览器
        CloseableHttpClient httpclient = HttpClients.createDefault();

        CloseableHttpResponse response= null;
        try{
            String localIp = InetAddress.getLocalHost().getHostAddress();
     /*       String remoteHost = request.getRemoteHost();
            System.out.println("host:>>>>>>>"+remoteHost);
            remoteHost= "36.112.125.94";
            String key = "0ee46e2751d0b380cfda4bc75cb33e91";
            String s1 = HttpClientUtil.doGetParam("http://whois.pconline.com.cn/ip.jsp", "ip","$_SERVER['REMOTE_ADDR']");
            logger.info("进入查询天气的方法");
             String s = HttpClientUtil.doGetParam("http://apis.juhe.cn/ip/ipNew","ip",remoteHost+key);*/
//        2.创建http请求 get、post 二者选一
            HttpGet httpGet = new HttpGet("http://apis.juhe.cn/ip/ipNew?ip=+"+localIp+"+&key=0ee46e2751d0b380cfda4bc75cb33e91");
//            3.执行请求，得到响应对象
            response = httpclient.execute(httpGet);
//        4.判断响应状态码是不是200，获取响应数据实体对象,200表示响应成功,一般用于get和post请求
            Map<String, Object> weatherMap = new HashMap<>();

            if (response.getStatusLine().getStatusCode() == 200) {
//        5.获取响应数据
                HttpEntity entity = response.getEntity();

                String content = EntityUtils.toString(entity, "utf-8");
                System.out.println("响应结果为---->" + content);
                Map<String, Object> map = (Map<String, Object>) JSON.parse(content);
                String result = map.get("result").toString();
                Map<String, Object> map1 = (Map<String, Object>) JSON.parse(result);
                String city = map1.get("City").toString();
                String weatherMsg = HttpClientUtil.doGetParam("http://wthrcdn.etouch.cn/weather_mini", "city", city);
                System.out.println(weatherMsg);
                JSONObject weatherJson = JSONObject.parseObject(weatherMsg);
                String data = weatherJson.getObject("data", String.class);
                JSONObject jo1 = JSONObject.parseObject(data);
                System.out.println(data);
                String localCity = jo1.getString("city");
                System.out.println(city);
                String forecast = jo1.getString("forecast");
                List<Weather> weathers = JSONArray.parseArray(forecast, Weather.class);
                weathers.stream().forEach(x -> System.out.println(x));
                weatherMap.put("city", localCity);
                weatherMap.put("weathers", weathers);
            }
        } catch (Exception e) {
            logger.info("查询失败", e);
        }finally {
//        6.关闭响应对象
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


